package assignment;

import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2025-02-25
 * Time: 22:05
 */
//编写代码实现两个线程增加同一个变量
// 使用 Semaphore 来控制线程安全.



public class Demo8 {

    private static Semaphore semaphore = new Semaphore(1);

    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                try {
                    increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                try {
                    increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(count);
    }

    private static void increase() throws InterruptedException {
        semaphore.acquire();
        count++;
        semaphore.release();
    }
}
